<template>
  <div>
    <el-dialog
      v-model="open"
      v-loading="loading"
      :before-close="cancle"
      :title="title"
      fullscreen
    >
      <customContainer ref="CabinetConfig" :config="config" />
    </el-dialog>
    <el-dialog v-model="open2" :before-close="cancle2" :title="title2">
      <el-form
        ref="query1"
        :model="query"
        label-width="120px"
        :rules="TransferOrderrules"
      >
        <el-form-item label="收货站点" prop="site">
          <el-select
            v-model="query.site"
            filterable
            style="width: 200px;"
            placeholder="请选择"
          >
            <el-option
              v-for="dict in dicts[DictDirection.收货站点]"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单/车牌" prop="expressNo">
          <el-input
            v-model="query.expressNo"
            filterable
            style="width: 200px;"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="运输方式" prop="transportMode">
          <el-select
            v-model="query.transportMode"
            filterable
            style="width: 200px;"
            placeholder="请选择"
          >
            <el-option
              v-for="dict in dicts[DictDirection.转运运输方式]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运费金额" prop="paidAmount">
          <el-input-number
            v-model="query.paidAmount"
            :min="1"
            style="width: 200px;"
            :controls="false"
            clearable
            placeholder="请输入运费金额"
          ></el-input-number>
          <!-- onkeyup="value=value.replace(/[^\d]|^[0]/g,'')" -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sumit2">确认</el-button>
          <el-button type="info" @click="cancle2">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <edit
      ref="editRef"
      @refush="initData"
    ></edit>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent, getCurrentInstance, defineEmits } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getlistTable, confirmCabinet, addtransfer } from '@/api/expressManager/yuOrder'

const { proxy } = getCurrentInstance() as any
const emit = defineEmits(['refush'])
const dicts = useDicts()
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.运输类型)
dicts.setDicts(DictDirection.包裹状态)
dicts.setDicts(DictDirection.收货站点)
dicts.setDicts(DictDirection.转运运输方式)
const edit = defineAsyncComponent(() => import('./edit.vue'))
const single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  {
    appContext: {
      config: {
        globalProperties: { $download },
      },
    },
  } = getCurrentInstance()
const queryParams = ref({
  cabinetNo: undefined,
  orderNo: undefined,
  loadingLocation: undefined,
  transportType: undefined,
  dateRange: undefined,
  createDate: undefined,
})
const btnloading = ref(false)
const TransferOrderrules = {
  site: [
    {
      required: true,
      message: '请选择收货站点',
      trigger: ['change'],
    },
  ],
  expressNo: [
    {
      required: true,
      message: '请选择快递单/车牌',
      trigger: ['change'],
    },
  ],
  transportMode: [
    {
      required: true,
      message: '请选择运输方式',
      trigger: ['change'],
    },
  ],
  paidAmount: [
    {
      required: true,
      message: '请输入运费金额',
      trigger: ['blur'],
    },
  ],
}
const CabinetConfig = ref(undefined)
const editRef = ref(undefined)
const loading = ref(false)
const open = ref(false)
const title = ref(null)
const cancle = () => {
  open.value = false
}
const open2 = ref(false)
const title2 = ref(null)
const cancle2 = () => {
  open2.value = false
  proxy.$refs.query1.resetFields()
}
const query = ref({
  site: '',
  expressNo: '',
  transportMode: '',
  paidAmount: '',
})
const query1 = ref(undefined)
const st = ref([])
const ca = ref([])
const idss = ref([])
// 修改
const addHandle = () => {
  editRef.value.open = true
  editRef.value.idss = JSON.parse(JSON.stringify(idss.value))
  editRef.value.transportTypes = JSON.parse(JSON.stringify(st.value))
  editRef.value.cab = JSON.parse(JSON.stringify(ca.value))
  editRef.value.initdata()
}
// 确认装柜
const onConfirm = () => {
  const data = {
    cabinetNo: ca.value.toString(),
    cabinetNoId: Number(idss.value.toString()),
  }
  ElMessageBox.confirm('是否装柜？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    btnloading.value = true
    confirmCabinet(data).then(res => {
      if (res.code == 200) {
        ElMessage.success('装柜成功')
        initData()
        refush()
        btnloading.value = false
      } else {
        ElMessage.error(res.msg)
        btnloading.value = false
      }
    }).catch(() => {
      btnloading.value = false
    })
  })
}
const exportMx = () => {
  const id = idss.value
  $download('order/cabinet/exportDetails', { ids: id }, `预排柜明细表格
  ${ new Date().getTime() }.xlsx`)
}
// 新增转运
const handleTransShipment = () => {
  open2.value = true
  title2.value = '新增转运'
}
const sumit2 = () => {
  const data = {
    cabinetNo: ca.value.toString(),
    cabinetId: Number(idss.value.toString()),
    expressNo: query.value.expressNo,
    paidAmount: query.value.paidAmount,
    site: query.value.site,
    transportMode: query.value.transportMode,
  }
  addtransfer(data).then(res => {
    if (res.code == 200) {
      ElMessage.success('转运成功')
      open2.value = false
      CabinetConfig.value.getList()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(rows)
  idss.value = rows.map((item) => item.id)
  st.value = rows.map((item) => item.transportType) 
  ca.value = rows.map((item) => item.cabinetNo) 
  single.value = rows.length != 1
  multiple.value = !rows.length
}
const initData = () => {
  CabinetConfig.value.getList()
}
const refush = () => {
  emit('refush')
}
defineExpose({
  open,
  title,
  loading,
})
const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '虚拟柜号',
            prop: 'cabinetNo',
            option: {
              placeholder: '请输入虚拟柜号',
            },
          },
          {
            label: '系统订单号',
            prop: 'orderNo',
          },
          {
            label: '装柜地点',
            prop: 'loadingLocation',
          },
          {
            type: 'select',
            label: '运输类型',
            prop: 'transportType',
            option: {
              dictInfo: { dict: DictDirection.运输类型 },
            },
          },
          {
            type: 'date-picker',
            label: '出货日期',
            prop: 'dateRange',
            option: {
              type: 'datetime',
            },
          },
          {
            type: 'date-picker',
            label: '创建日期',
            prop: 'createDate',
            option: {
              type: 'datetime',
            },
          },
         
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '修改',
          type: 'primary',
          onClick: addHandle,
          disabled: single.value,
        },
        {
          title: '确认装柜',
          onClick: onConfirm,
          type: 'primary',
          disabled: single.value,
        },
        {
          title: '新增转运',
          onClick: handleTransShipment,
          type: 'primary',
          disabled: single.value,
        },
        {
          title: '导出预排柜明细',
          onClick: exportMx,
          type: 'warning',
          disabled: multiple.value,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
       
          { label: '虚拟柜号', align: 'center', prop: 'cabinetNo' },
          { label: '状态',
            align: 'center',
            prop: 'status',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'status',
            } },
          { label: '出货总实重', align: 'center', prop: 'totalSolidWeight' },
          { label: '出货总材积重（方）', align: 'center', prop: 'totalVolumeWeight' },
          { label: '出货件数', align: 'center', prop: 'totalPiece' },
          { label: '出货票数', align: 'center', prop: 'votesNumber' },
          { label: '运输类型',
            align: 'center',
            prop: 'transportType',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          { label: '创建时间', align: 'center', prop: 'createDate' },
          { label: '创建人', align: 'center', prop: 'createUser' },
          { label: '备注', align: 'center', prop: 'remarks' },
         
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getlistTable,
      customKey: 'express/mainBusiness/oceanShipping/outputWarehouseManagement',
    }
  },
  set(v) {
    return v
  },
})
</script>